package com.it.share;

import cn.hutool.core.util.RandomUtil;
import lombok.AllArgsConstructor;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class MgDataSource extends SingleConnectionDataSource {
    private final AtomicInteger index;
    private final List<DataSource> ds;

    public MgDataSource(List<DataSource> ds) {
        this.ds = ds;
        index = new AtomicInteger(0);
    }

    @Override
    public Connection getConnection() throws SQLException {
        Connection connection = ds.get(index.get()).getConnection();

        int b = index.incrementAndGet();
        if (b == ds.size()) {
            index.set(0);
        }

        return connection;
    }
}
